'''
    Date    2021/3/31/0031
    Name    Google_Title
    author: Willim
    desc: 
'''
import random
import requests, datetime, time
from lxml import etree

from loguru import logger


class Google_Title_:

    def main(self, title):
        redis_keys = [
            "pdfdown:google-search1",
            "pdfdown:google-search2",
            "pdfdown:google-search3",
            "pdfdown:google-search4",
        ]
        key = random.choice(redis_keys)
        if not key:
            logger.error("获取google 检索秘钥错误！")
            return {}

        def request_title(titile):
            data = []
            for x in range(3):
                try:
                    headers = {"token": "s5FYA6re6sp4IiRV"}
                    url = 'https://scholar.newacademic.net/api/home/search/scholar/?page=1&oa=0&key_list=[{"field":"intitle","value":"' + titile + '","mode":"exact"}]&order_type=2&is_sensitive=1&lookup=2'
                    response = requests.get(url, headers=headers)
                    response_json = response.json()
                    data = response_json.get("data", {})
                    if not data:
                        logger.error("google 检索结果为空！")
                        break
                    data = data.get("data", {}).get("art_list", [])
                    return data
                except:
                    logger.exception("google 标题检索失败!")
            return data

        result = request_title(title)
        if result and len(result) <= 3:
            first_result = result[0]
            title = first_result.get("title", "")
            title = str(title).replace("<b>", "").replace("</b>", "")
            titleUrl = first_result.get("titleUrl", "")
            openUrl = first_result.get("openUrl", "")
            return {
                "openUrl": openUrl,
                "finalHref": titleUrl,
                "title": title,
            }
        else:
            return {}


Google_Title_ = Google_Title_()
if __name__ == '__main__':
    title_lis = [
        # "Bearing mobility affects tibial strain in mobile-bearing unicompartmental knee arthroplasty",
        # "Performance Improvement of Flexible Antennas for Maritime Communications"
        "Is the Profession of Sport Psychology an Illusion?"
    ]
    for title in title_lis:
        result = Google_Title_.main(title)
        print(result)
